<?php
/**
 * Created by PhpStrom
 * User: 郭碧云
 * Date: 2021/7/12 9:01
 * Desc:
 */

namespace App\Http\Controllers\Admin;


use App\Facades\Code;
use App\Http\Controllers\BaseAdminController;
use App\Lib\Common;
use App\Lib\FormulaInterpreter\Compiler;
use App\Lib\Logger;
use App\Service\AdminUserService;
use App\Service\CategoryService;
use App\Service\QuestionContentService;
use App\Service\QuestionService;
use App\Service\QuestionTypeService;
use App\Service\TagService;
use Illuminate\Support\Facades\DB;

class QuestionController extends BaseAdminController
{
    protected $questionTypeService = "";
    protected $questionService = "";
    protected $questionContentService = "";
    protected $categoryService = "";
    protected $category = [];

    public function _init() {
        $this->questionTypeService = new QuestionTypeService();
        $this->questionService = new QuestionService();
        $this->questionContentService = new QuestionContentService();
        $this->categoryService = new CategoryService();
        //考试科目分类
        $category=getData("CategoryDataTag",["scope_exam" => 1]);
        $this->category = Common::getTree($category);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index() {
        $where = $this->questionService->getWhere($this->request->all());
        $data = $this->questionService->getList(["id", "category_id", "type_id", "question", "level", "creator", "tag_id", "org_id", "version_id", "created_at", "updated_at"], $where, "", ["created_at" => "desc"]);
        $types = (new QuestionTypeService())->getAll(["id", "name"]);
        $creators = $this->questionService->getUser();
        $orgs = Common::getTree(getData("OrgDataTag"));
        $version = getData("QuestionVersionDataTag");
        return view("admin.question.index", ["question" => $data, "category" => json_encode($this->category), "types" => json_encode($types), "creators" => json_encode($creators), "orgs" => json_encode($orgs), "version" => json_encode($version)]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        if ($this->request->isMethod("get")) {
            //组织机构
            $orgs = json_encode(Common::getTree(getData('OrgDataTag')));
            //题型
            $types = json_encode($this->questionTypeService->getAll());
            //版本
            $version = json_encode(getData('QuestionVersionDataTag'));
            //难度level
            $level = Code::getItemsByCode("QUESTION_LEVEL");
            return view("admin.question.create", ["orgs" => $orgs, "types" => $types, "version" => $version, "categroy" => json_encode($this->category), 'level' => $level]);
        } else {
            $data = $this->request->all();
            $this->validateData($data["data"], "checkData");
            //验证tag_id
            $category = $this->categoryService->first(["id"=>$data["data"]["category_id"]]);
            if(!empty($category["exam_tag_group"])){
                $this->validateData(["tag_id"=>$data["data"]["tag_id"]], "checkTagID");
            }
            return $this->store($data);
        }

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    private function store($data) {
        $data = $this->questionService->getData($data["data"]);
        //保存基本数据
        $basic = $this->questionService->create($data);
        if (!empty($basic)) {
            $conData = ["question_id" => $basic["id"], "explanation" => $data["explanation"], "content" => json_encode($data["content"], JSON_UNESCAPED_SLASHES), "answer" => json_encode($data["answer"], JSON_UNESCAPED_SLASHES)];
            $result = $this->questionContentService->create($conData);
            if (!empty($result)) {
                $this->log(Logger::LOG_LEVEL_INFO, Logger::QUESTION, "create", "新增试题{$basic['id']}添加成功", $data);
                return $this->tempNotice("admin.question.index", "添加成功");
            } else {
                $this->log(Logger::LOG_LEVEL_ERROR, Logger::QUESTION, "create", "新增试题{$basic['id']}内容添加失败", $result);
                return $this->tempNotice("admin.question.index", "试题题干添加成功，内容添加失败", "warning");
            }
        }
        $this->log(Logger::LOG_LEVEL_ERROR, Logger::QUESTION, "create", "试题新增失败", $data);
        return $this->tempNotice("admin.question.index", "试题添加失败", "error");
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        $this->validateData(["id" => $id], 'checkId');
        $info = $this->questionService->first(["id" => $id]);
        $info["content"]["content"] = json_decode($info["content"]["content"], true);
        $info["content"]["answer"] = json_decode($info["content"]["answer"], true);
        if($info["type"]["choice_type"]==6){
            //计算题返回结果
            $info["content"]["answer"] = $this->questionService->getResult($info["content"]["answer"]);
        }
        return view("admin.question.show", ["info" => $info]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        $this->validateData(["id" => $id], 'checkId');
        if ($this->request->isMethod("get")) {
            $info = $this->questionService->first(["id" => $id]);
            $info["content"]["content"] = json_decode($info["content"]["content"], true);
            $info["content"]["answer"] = json_decode($info["content"]["answer"], true);
            //组织机构
            $orgs = json_encode(Common::getTree(getData('OrgDataTag')));
            //题型
            $types = json_encode($this->questionTypeService->getAll());
            //版本
            $version = json_encode(getData('QuestionVersionDataTag'));
            //难度level
            $level = Code::getItemsByCode("QUESTION_LEVEL");
            //获取标签
            $tag = (new TagService())->getAll();
            return view("admin.question.edit", ["info" => $info, "tag" => json_encode($tag), "orgs" => $orgs, "types" => $types, "version" => $version, "categroy" => json_encode($this->category), 'level' => $level]);
        } else {
            $data = $this->request->all();
            $this->validateData($data["data"], "checkData");
            //验证tag_id
            $category = $this->categoryService->first(["id"=>$data["data"]["category_id"]]);
            if(!empty($category["exam_tag_group"])){
                $this->validateData(["tag_id"=>$data["data"]["tag_id"]], "checkTagID");
            }
            return $this->update($id, $data["data"]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    private function update($id, $data) {
        $data = $this->questionService->getData($data);
        $upQuestion = $this->questionService->update($id, $data);
        if ($upQuestion) {
            $conData = ["content" => json_encode($data["content"], JSON_UNESCAPED_SLASHES), "answer" => json_encode($data["answer"], JSON_UNESCAPED_SLASHES)];
            $result = $this->questionContentService->saveUpdate($id, $conData);
            if ($result) {
                $this->log(Logger::LOG_LEVEL_INFO, Logger::QUESTION, "edit", "试题{$id}更新成功", $data);
                return $this->tempNotice("admin.question.index", "更新成功");
            } else {
                $this->log(Logger::LOG_LEVEL_ERROR, Logger::QUESTION, "edit", "试题{$id}内容更新失败", $conData);
                return $this->tempNotice("admin.question.index", "试题题干更新成功，内容更新失败", "warning");
            }
        }
        $this->log(Logger::LOG_LEVEL_ERROR, Logger::QUESTION, "edit", "试题{$id}更新失败", $data);
        return $this->tempNotice("admin.question.index", "更新失败", "error");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */

    public function destroy(){
        $ids = $this->request->all();
        $result = $this->questionService->destroy($ids["ids"]);
        if (!$result) {
            $this->log(Logger::LOG_LEVEL_ERROR, Logger::QUESTIONTYPE, 'destroy', "试题{$ids["ids"]}删除失败", ['del_id' => $ids["ids"]]);
            return $this->error(80001, "删除失败");
        }
//        $this->questionContentService->delete(["question_id" => $ids["ids"]]);
        return $this->layuiDataSuccess("", 0, "删除成功");
    }
}
